<template>
  <div class="create-tool">
    <h1 class="page-title">新增MCP工具</h1>
    
    <el-form 
      ref="toolFormRef" 
      :model="toolForm" 
      :rules="rules" 
      label-width="120px" 
      class="tool-form"
      :disabled="loading"
    >
      <el-form-item label="工具名称" prop="name">
        <el-input v-model="toolForm.name" placeholder="请输入MCP工具名称"></el-input>
      </el-form-item>
      
      <el-form-item label="英文名称" prop="english_name">
        <el-input v-model="toolForm.english_name" placeholder="请输入英文名称（用于API调用）"></el-input>
      </el-form-item>
      
      <el-form-item label="工具描述" prop="description">
        <el-input
          v-model="toolForm.description"
          type="textarea"
          :rows="4"
          placeholder="请详细描述该MCP工具的功能和用途"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="分类" prop="category_id">
        <el-select v-model="toolForm.category_id" placeholder="请选择分类" style="width: 100%">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="工具图标" prop="icon">
        <el-upload
          class="avatar-uploader"
          action="/api/upload"
          :show-file-list="false"
          :on-success="handleIconSuccess"
          :before-upload="beforeIconUpload"
        >
          <img v-if="toolForm.icon" :src="toolForm.icon" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">建议上传正方形图片，大小不超过200KB</div>
      </el-form-item>
      
      <el-divider>MCP服务配置</el-divider>
      
      <el-form-item label="MCP服务配置" prop="mcp_config">
        <el-tabs v-model="configTab" class="config-tabs">
          <el-tab-pane label="服务器配置" name="mcpServers">
            <div class="mcp-servers">
              <div v-for="(server, serverKey) in mcpServers" :key="serverKey" class="server-item">
                <div class="server-header">
                  <h3>{{ serverKey }}</h3>
                  <el-button 
                    type="danger" 
                    size="small" 
                    circle 
                    @click="removeMcpServer(serverKey)"
                    :icon="Delete"
                  ></el-button>
                </div>
                
                <el-form-item label="服务器URL">
                  <el-input v-model="mcpServers[serverKey].url" placeholder="服务器URL"></el-input>
                </el-form-item>
                
                <el-divider v-if="Object.keys(mcpServers).indexOf(serverKey) < Object.keys(mcpServers).length - 1"></el-divider>
              </div>
              
              <div v-if="!Object.keys(mcpServers).length" class="empty-servers">
                <el-empty description="暂无MCP服务器配置" />
              </div>
              
              <div class="add-server-section">
                <el-form-item label="服务器名称">
                  <el-input v-model="newServerName" placeholder="输入新服务器名称"></el-input>
                </el-form-item>
                <el-button type="primary" @click="addMcpServer" :disabled="!newServerName">添加MCP服务器</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="JSON编辑" name="json">
            <el-input
              v-model="mcpConfigJson"
              type="textarea"
              :rows="15"
              placeholder="请输入MCP服务配置JSON，如： { 'mcpServers': { 'amap-amap-sse': { 'url': 'https://mcp.amap.com/sse?key=xxx' } } }"
              @input="handleConfigJsonInput"
            ></el-input>
            <div class="json-error" v-if="configJsonError">{{ configJsonError }}</div>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      
      <div class="form-actions">
        <el-button @click="$router.push('/')">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">创建MCP工具</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

export default {
  name: 'CreateTool',
  components: {
    Plus,
    Delete
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 表单引用
    const formData = reactive({
      name: '',
      english_name: '',
      description: '',
      category_id: '',
      icon: '',
      mcp_config: {
        mcpServers: {}
      }
    })
    
    // MCP服务配置
    const mcpServers = ref({})
    const configTab = ref('mcpServers')
    const mcpConfigJson = ref('{\n  "mcpServers": {}\n}')
    const configJsonError = ref('')
    const newServerName = ref('')
    const loading = ref(false)
    const toolFormRef = ref(null)
    
    // 初始化获取分类列表
    const categories = ref([])
    const getCategories = async () => {
      try {
        await store.dispatch('fetchCategories')
        categories.value = store.state.categories || []
      } catch (error) {
        ElMessage.error('获取分类列表失败')
        console.error(error)
      }
    }
    getCategories()
    
    // 添加MCP服务器
    const addMcpServer = () => {
      if (!newServerName.value) return
      
      // 创建新的服务器配置
      mcpServers.value[newServerName.value] = {
        url: ''
      }
      
      updateMcpConfig()
      newServerName.value = ''
    }
    
    // 移除MCP服务器
    const removeMcpServer = (serverKey) => {
      delete mcpServers.value[serverKey]
      updateMcpConfig()
    }
    
    // 更新MCP配置
    const updateMcpConfig = () => {
      formData.mcp_config = {
        mcpServers: { ...mcpServers.value }
      }
      mcpConfigJson.value = JSON.stringify(formData.mcp_config, null, 2)
    }
    
    // 处理配置JSON输入
    const handleConfigJsonInput = (value) => {
      try {
        const config = JSON.parse(value)
        formData.mcp_config = config
        
        // 更新MCP服务器配置
        if (config.mcpServers) {
          mcpServers.value = { ...config.mcpServers }
        } else {
          mcpServers.value = {}
        }
        
        configJsonError.value = ''
      } catch (e) {
        configJsonError.value = '无效的JSON: ' + e.message
      }
    }
    
    // 图标上传处理
    const handleIconSuccess = (res, file) => {
      // 这里假设后端返回的是图片URL
      formData.icon = res.url
    }
    
    const beforeIconUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt200K = file.size / 1024 < 200
      
      if (!isImage) {
        ElMessage.error('上传图标只能是图片格式!')
      }
      
      if (!isLt200K) {
        ElMessage.error('上传图标大小不能超过200KB!')
      }
      
      return isImage && isLt200K
    }
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入工具名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
      ],
      english_name: [
        { required: true, message: '请输入英文名称', trigger: 'blur' },
        { pattern: /^[a-z][a-z0-9_]*$/, message: '只能包含小写字母、数字和下划线，且必须以字母开头', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入工具描述', trigger: 'blur' }
      ],
      category_id: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ]
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!toolFormRef.value) return
      
      // 表单验证
      try {
        await toolFormRef.value.validate()
      } catch (error) {
        return
      }
      
      // 更新MCP配置
      updateMcpConfig()
      
      // 确保MCP配置数据被正确包含
      console.log('提交的MCP配置:', formData.mcp_config)
      
      // 提交数据
      loading.value = true
      try {
        await store.dispatch('createTool', formData)
        ElMessage.success('创建MCP工具成功')
        router.push('/')
      } catch (error) {
        ElMessage.error('创建失败: ' + error.message)
        console.error('Error creating tool:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 初始化
    updateMcpConfig()
    
    return {
      toolForm: formData,
      rules,
      mcpServers,
      categories,
      configTab,
      mcpConfigJson,
      configJsonError,
      newServerName,
      loading,
      toolFormRef,
      addMcpServer,
      removeMcpServer,
      handleIconSuccess,
      beforeIconUpload,
      handleConfigJsonInput,
      submitForm,
      Delete
    }
  }
}
</script>

<style scoped>
.create-tool {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  margin-bottom: 30px;
  text-align: center;
  color: #303133;
}

.tool-form {
  background-color: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.server-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.server-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.server-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.add-server-section {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e0e0e0;
}

.empty-servers {
  padding: 30px 0;
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 128px;
  height: 128px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  gap: 20px;
}

.json-error {
  color: #f56c6c;
  margin-top: 10px;
  font-size: 12px;
}

.config-tabs {
  width: 100%;
}
</style> 